import os
import random
from typing import Optional, Dict, Any, List
import time
from datetime import datetime
from .word_study_manager import WordStudyManager

class TypingGame:
    def __init__(self):
        self.study_manager = WordStudyManager()
        self.current_word_info = None
        self.current_index = 0
        self.total_words = 0
        self.selected_words = []
        self.start_time = 0
        self.mode = "practice"  # "practice" or "study"
        
    def set_mode(self, mode: str):
        """设置游戏模式
        
        Args:
            mode: "practice" 或 "study"
        """
        self.mode = mode
        
    def load_wordbank(self, wordbank_name: str) -> bool:
        """加载词库
        
        Args:
            wordbank_name: 词库名称
            
        Returns:
            是否成功加载
        """
        return self.study_manager.load_wordbank(wordbank_name)
        
    def get_practice_words(self, count: int = 10) -> List[Dict]:
        """获取练习单词
        
        Args:
            count: 单词数量
            
        Returns:
            单词列表
        """
        if self.mode == "study":
            # 学习模式：获取新单词和需要复习的单词
            new_words = self.study_manager.get_daily_new_words(count)
            review_words = self.study_manager.get_words_to_review()
            self.selected_words = new_words + review_words
        else:
            # 练习模式：随机获取单词
            all_words = self.study_manager.get_all_words()
            random.shuffle(all_words)
            self.selected_words = all_words[:count]
            
        self.total_words = len(self.selected_words)
        self.current_index = 0
        self.start_time = time.time()
        return self.selected_words
        
    def get_next_word(self) -> Optional[Dict]:
        """获取下一个单词
        
        Returns:
            单词信息字典，如果没有更多单词则返回 None
        """
        if self.current_index < len(self.selected_words):
            self.current_word_info = self.selected_words[self.current_index]
            self.start_time = time.time()
            return self.current_word_info
        return None
        
    def check_input(self, user_input: str) -> Dict:
        """检查用户输入
        
        Args:
            user_input: 用户输入的文本
            
        Returns:
            包含检查结果的字典
        """
        if not self.current_word_info:
            return {}
            
        is_correct = user_input.strip().lower() == self.current_word_info["word"].lower()
        elapsed_time = time.time() - self.start_time
        
        # 更新学习进度
        if self.mode == "study":
            self.study_manager.update_word_progress(self.current_word_info["word"], is_correct)
        
        return {
            "word": self.current_word_info["word"],
            "is_correct": is_correct,
            "wpm": int(len(user_input.split()) * 60 / max(1, elapsed_time)),
            "elapsed_time": elapsed_time
        }
        
    def move_to_next_word(self):
        """移动到下一个单词"""
        self.current_index += 1
        return self.get_next_word()
        
    def get_progress(self) -> Dict:
        """获取进度信息
        
        Returns:
            进度信息字典
        """
        return {
            "current": self.current_index + 1,
            "total": self.total_words,
            "percentage": round((self.current_index + 1) / max(1, self.total_words) * 100, 1)
        }
        
    def get_stats(self) -> Dict:
        """获取统计信息
        
        Returns:
            统计信息字典
        """
        if self.mode == "study":
            return self.study_manager.get_learning_stats()
        else:
            return {
                "total_words": self.total_words,
                "completed_words": self.current_index,
                "progress_percentage": round(self.current_index / max(1, self.total_words) * 100, 1)
            }
